package com.rui.sideup.test.socket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class MyClient extends WebSocketClient {

    public MyClient(String url) throws URISyntaxException {
        super(new URI(url));
    }

    public static void main(String[] args) {
        try {
            MyClient client = new MyClient("ws://10.23.104.60:60008");
            client.connect();
            while (!client.getReadyState().equals(ReadyState.OPEN)) {
                Thread.sleep(1000);
                System.out.println("还没有打开");
            }
            System.out.println("建立websocket连接");

            client.send("客户端发送测试数据~");
        } catch (URISyntaxException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onOpen(ServerHandshake shake) {
        System.out.println("握手...");
        for (Iterator<String> it = shake.iterateHttpFields(); it.hasNext(); ) {
            String key = it.next();
            System.out.println(key + ":" + shake.getFieldValue(key));
        }
    }

    @Override
    public void onMessage(String paramString) {
        System.out.println("接收到String消息：" + paramString);
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        String str = StandardCharsets.UTF_8.decode(bytes).toString();
        bytes.flip();

        System.out.println("接收到ByteBuffer消息：" + str);
    }

    @Override
    public void onClose(int paramInt, String paramString, boolean paramBoolean) {
        System.out.println("关闭...");
    }

    @Override
    public void onError(Exception e) {
        System.out.println("异常" + e);

    }

}